package com.jindun.paper.service.impl;

import java.util.Calendar;
import java.util.Date;

import org.springframework.stereotype.Component;

@Component
public class MonthlyCalculator {

	public Date [] calc(int begin, Date currentDate) {
		Date beginDate = null;
		Date endDate = null;
		Calendar cal1 = Calendar.getInstance();
		cal1.setTime(currentDate);
		cal1.set(Calendar.HOUR, 0);
		cal1.clear(Calendar.MINUTE);
		cal1.clear(Calendar.SECOND);
		
		Calendar cal2 = Calendar.getInstance();
		cal2.setTime(currentDate);
		cal2.set(Calendar.HOUR, 23);
		cal2.set(Calendar.MINUTE, 59);
		cal2.set(Calendar.SECOND, 39);
		
		if (begin == -1) {
			cal1.set(Calendar.DATE, 1);
			beginDate = cal1.getTime();
		
			cal2.set(Calendar.DATE, cal2.getLeastMaximum(Calendar.DAY_OF_MONTH));
			endDate = cal2.getTime();
		} else {
			
			begin = begin >  cal1.getLeastMaximum(Calendar.DATE) ?  cal1.getLeastMaximum(Calendar.DATE) : begin;
		
			cal1.set(Calendar.DATE, begin);
			if (currentDate.compareTo(cal1.getTime()) > 0) {
				beginDate = cal1.getTime();
				cal1.add(Calendar.MONTH, 1);
				cal1.add(Calendar.DATE, -1);
				cal1.set(Calendar.HOUR, 23);
				cal1.set(Calendar.MINUTE, 59);
				cal1.set(Calendar.SECOND, 39);
				endDate = cal1.getTime();
			} else {
				cal1.add(Calendar.DATE, -1);
				cal1.set(Calendar.HOUR, 23);
				cal1.set(Calendar.MINUTE, 59);
				cal1.set(Calendar.SECOND, 39);
				endDate = cal1.getTime();
				
				cal1.setTime(endDate);
				cal1.set(Calendar.HOUR_OF_DAY, 0);
				cal1.clear(Calendar.MINUTE);
				cal1.clear(Calendar.SECOND);
				cal1.add(Calendar.MONTH, -1);
				cal1.add(Calendar.DATE, 1);
				
				
				beginDate = cal1.getTime();
			}
		}
		
		return new Date [] {beginDate, endDate};
	}
}
